import win32gui
import cv2
import numpy as np
import win32api
import yaml
import os
import pyautogui
from threading import Thread
from pynput import keyboard

WIN_NAME = "ArkAscended"
DEBUG_IMG = []
DEBUG_CONFIG = False
DEBUG = False
SCAN_INTER = 100
AUTO_BACK = 10
X_OFFSET = 0
Y_OFFSET = 0
REAL_W = 640
REAL_H = 480

roi_exp = [0]
stop = False
save_name = 0
img = []

def load_cfg():
    global WIN_NAME
    global DEBUG_IMG
    global DEBUG_CONFIG
    global DEBUG
    global SCAN_INTER
    global AUTO_BACK
    global X_OFFSET
    global Y_OFFSET
    global REAL_W
    global REAL_H
    file_path = "cfg.yaml"
    if not os.path.exists(file_path):
        return
    else:
        with open(file_path, 'r') as file:
            try:
                cfg_data = yaml.safe_load(file)
                DEBUG_IMG = cfg_data['debug image']
                DEBUG_CONFIG = cfg_data['config debug']
                DEBUG = cfg_data['runing debug']
                SCAN_INTER = cfg_data['scanner interval']
                AUTO_BACK = cfg_data['auto back']
                X_OFFSET = cfg_data['x offset']
                Y_OFFSET = cfg_data['y offset']
                REAL_W = cfg_data['real width']
                REAL_H = cfg_data['real height']
                print(cfg_data)
            except yaml.YAMLError as e:
                print(e)

def check_windiw():
    win_names = set()
    def get_window_title(window, nouse):
        if win32gui.IsWindow(window) and \
                win32gui.IsWindowEnabled(window) and \
                win32gui.IsWindowVisible(window):
            win_names.add(win32gui.GetWindowText(window))

    win32gui.EnumWindows(get_window_title, 0)
    win_list = [_ for _ in win_names if _]
    if WIN_NAME in win_list:
        return True
    return False

def get_win_rect():
    win = win32gui.FindWindow(0, WIN_NAME)  # 根据窗口名称获取窗口对象
    x1, y1, x2, y2 = win32gui.GetWindowRect(win)
    w_max = win32api.GetSystemMetrics(0)
    h_max = win32api.GetSystemMetrics(1)
    if x1 < 0 or y1 < 0 or x2 >= w_max or y2 >= h_max:
        return 0, 0, 0, 0
    x1 += X_OFFSET     # 去除边缘
    y1 += Y_OFFSET    # 去除边缘
    return x1, y1, REAL_W, REAL_H

def get_img(win_rect):
    screenshot = pyautogui.screenshot(region=win_rect)
    screenshot_np = np.array(screenshot)
    img = cv2.resize(screenshot_np, dsize=(640, 480))
    return cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

def run():
    global img
    print("power by lzs")
    while True:
        if stop:
            break
        cv2.waitKey(SCAN_INTER)
        win_rect = get_win_rect()
        if win_rect == (0, 0, 0, 0):
            print("应用窗口请勿靠近屏幕边缘")
            continue
        img = get_img(win_rect)
        cv2.imshow("Real-time Screen Capture", img)

def keyboard_Listen():
    def key_release(key):
        global stop
        global save_name
        global img
        if key == keyboard.Key.esc:
            stop = True
            if DEBUG:
                print("退出")
            exit()
        elif key == keyboard.Key.alt_l:
            save_name += 1
            cv2.imwrite(f"{save_name}.png", img)
            print(f"{save_name}.png save ok")
    with keyboard.Listener(on_release=key_release) as listener:
        listener.join()

load_cfg()
check_windiw()
th1 = Thread(target=run)
th2 = Thread(target=keyboard_Listen)
th1.start()
th2.start()
th1.join()

